/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.thinkgem.jeesite.modules.teach.web;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.thinkgem.jeesite.common.ConstantEnum;
import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.persistence.ReturnObject;
import com.thinkgem.jeesite.common.service.CrudService;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.common.utils.excel.ExportExcel;
import com.thinkgem.jeesite.common.web.ExcelController;
import com.thinkgem.jeesite.modules.act.entity.Act;
import com.thinkgem.jeesite.modules.act.utils.ActUtils;
import com.thinkgem.jeesite.modules.sys.security.FormAuthenticationFilter;
import com.thinkgem.jeesite.modules.sys.service.SystemService;
import com.thinkgem.jeesite.modules.sys.utils.UserUtils;
import com.thinkgem.jeesite.modules.teach.entity.TpTeachAchievement;
import com.thinkgem.jeesite.modules.teach.entity.TpTeachMaterial;
import com.thinkgem.jeesite.modules.teach.service.TpTeachMaterialService;

/**
 * 教材建设Controller
 * @author 康力
 * @version 2018-03-11
 */
@Controller
@RequestMapping(value = "${adminPath}/teach/tpTeachMaterial")
public class TpTeachMaterialController extends ExcelController<TpTeachMaterial> {

	@Autowired
	private TpTeachMaterialService tpTeachMaterialService;
	@Autowired
	private SystemService systemService;

	@ModelAttribute
	public TpTeachMaterial get(@RequestParam(required=false) String id) {
		TpTeachMaterial entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = tpTeachMaterialService.get(id);
		}
		if (entity == null){
			entity = new TpTeachMaterial();
		}
		//根据拥有当前菜单角色的最大的数据范围 判断是否是获取本人数据
		entity.setUserDataScope(systemService.getCurUserDataScopeByPermission("teach:tpTeachMaterial:view"));
		if (entity.getIsNewRecord() && entity.getUserDataScope() == 0) {// 个人数据权限，获取个人信息
			entity.setUser(UserUtils.getUser());// 设置人员
			if (entity.getUser() != null) {
				entity.setDepartment(entity.getUser().getOffice());// 设置科室
				if (entity.getDepartment() != null) {
					// 设置教研室
					entity.setTrc(systemService.findParentByOfficeId(entity.getDepartment().getId()));
				}
			}
		}
		return entity;
	}
	
	@RequiresPermissions("teach:tpTeachMaterial:view")
	@RequestMapping(value = {"list", ""})
	public String list(TpTeachMaterial tpTeachMaterial, HttpServletRequest request, HttpServletResponse response, Model model) {
		String str = request.getRequestURI().replaceFirst(request.getContextPath()+Global.getConfig("adminPath"), "");
		model.addAttribute("remark",systemService.getRemark(str));
		//根据拥有当前菜单角色的最大的数据范围 判断是否是获取本人数据
		tpTeachMaterial.setUserDataScope(systemService.getCurUserDataScopeByPermission("teach:tpTeachMaterial:view"));
		if(tpTeachMaterial.getUserDataScope() == 0){
			tpTeachMaterial.setUser(UserUtils.getUser());
		}else{//获得当前登录人部门下的数据
			if(tpTeachMaterial.getDepartment() == null)tpTeachMaterial.setDepartment(UserUtils.getUser().getOffice());
		}
		Page<TpTeachMaterial> page = tpTeachMaterialService.findPage(new Page<TpTeachMaterial>(request, response), tpTeachMaterial);
		if(WebUtils.isTrue(request, FormAuthenticationFilter.DEFAULT_MOBILE_PARAM)){//移动端请求，封装数据
			ReturnObject rtobj = new ReturnObject();
			rtobj.setResult(ConstantEnum.success.getCode());
			rtobj.setMsg(ConstantEnum.success.getName());
			rtobj.setData(page);
			return renderString(response, rtobj);
		}
		model.addAttribute("page", page);
		return "modules/teach/tpTeachMaterialList";
	}

	@RequiresPermissions("teach:tpTeachMaterial:view")
	@RequestMapping(value = "form")
	public String form(TpTeachMaterial tpTeachMaterial, Model model, HttpServletRequest request, HttpServletResponse response) {
		//如果为新增数据并且数据权限为个人数据的情况下，启动审批流程
		String viewName = "";
		if(tpTeachMaterial == null ||
				(tpTeachMaterial.getStatus()!= null && tpTeachMaterial.getStatus() == 2)||
				(StringUtils.isBlank(tpTeachMaterial.getId())&&StringUtils.isBlank(tpTeachMaterial.getAct().getProcInsId()))){
			//根据流程名称获取最新的流程实例名称
			String procDefId = null;
			if(systemService.getCurUserDataScopeByPermission("teach:tpTeachMaterial:view") == 0){
				procDefId =  systemService.getprocDefIdByProcDefKey(ActUtils.TP_TEACH_MATERIAL[0]);
			}
			Act act = new Act();
			act.setProcDefId(procDefId);
			tpTeachMaterial.setAct(act);
			viewName="tpTeachMaterialForm";
		} else if (tpTeachMaterial.getAct() != null && tpTeachMaterial.getAct().getTaskDefKey() != null
				&& tpTeachMaterial.getAct().getTaskDefKey().startsWith("audit")
				&&tpTeachMaterial.getAct().isTodoTask()) {
			viewName="tpTeachMaterialAudit";
		}else{
			viewName="tpTeachMaterialView";
			//如果实体类内容未查出，使用ProcInsId查询
			Act act = tpTeachMaterial.getAct();
			if(StringUtils.isBlank(tpTeachMaterial.getId()) && act != null
					&& StringUtils.isNotBlank(act.getProcInsId())){
				tpTeachMaterial.setProcInsId(act.getProcInsId());
				List<TpTeachMaterial> list = tpTeachMaterialService.findList(tpTeachMaterial);
				if(list.size() == 1){
					tpTeachMaterial = list.get(0);
					tpTeachMaterial.setAct(act);
				}
			}
		}
		if(WebUtils.isTrue(request, FormAuthenticationFilter.DEFAULT_MOBILE_PARAM)){//移动端请求，封装数据
			ReturnObject rtobj = new ReturnObject();
			rtobj.setResult(ConstantEnum.success.getCode());
			rtobj.setMsg(ConstantEnum.success.getName());
			ExportExcel ex = new ExportExcel("教材建设", TpTeachMaterial.class);
			tpTeachMaterial = ex.getMobileDataList(tpTeachMaterial);
			tpTeachMaterial.setPropertyNameMap(ex.getPropertyNameMap());
			rtobj.setData(tpTeachMaterial);
			return renderString(response, rtobj);
		}
		model.addAttribute("tpTeachMaterial", tpTeachMaterial);
		return "modules/teach/"+viewName;
	}

	@RequiresPermissions("teach:tpTeachMaterial:edit")
	@RequestMapping(value = "save")
	public String save(TpTeachMaterial tpTeachMaterial, Model model, RedirectAttributes redirectAttributes, HttpServletRequest request, HttpServletResponse response) {
		if (!beanValidator(model, tpTeachMaterial)){
			return form(tpTeachMaterial, model,request,response);
		}
		tpTeachMaterialService.save(tpTeachMaterial);
		addMessage(redirectAttributes, "保存教材建设成功");
		return "redirect:"+Global.getAdminPath()+"/teach/tpTeachMaterial/?repage";
	}
	
	@RequiresPermissions("teach:tpTeachMaterial:edit")
	@RequestMapping(value = "delete")
	public String delete(TpTeachMaterial tpTeachMaterial, RedirectAttributes redirectAttributes) {
		tpTeachMaterialService.delete(tpTeachMaterial);
		addMessage(redirectAttributes, "删除教材建设成功");
		return "redirect:"+Global.getAdminPath()+"/teach/tpTeachMaterial/?repage";
	}

	@Override
	protected TpTeachMaterialService getService() {
		return tpTeachMaterialService;
	}
	@Override
	public String getTitle() {
		return "我的教材建设";
	}

	@Override
	public String defaultStr() {
		return "/teach/tpTeachMaterial/?repage";
	}

	@Override
	public CrudService baseService() {
		return tpTeachMaterialService;
	}
	@Override
	@RequiresPermissions("teach:tpTeachPatent:view")
	@RequestMapping(value = "import/template")
	public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes,TpTeachMaterial t) {
		return super.importFileTemplate(response,redirectAttributes,t);
	}

	@Override
	@RequiresPermissions("teach:tpTeachPatent:edit")
	@RequestMapping(value = "import", method= RequestMethod.POST)
	public String importFile(MultipartFile file, RedirectAttributes redirectAttributes, TpTeachMaterial data) {
		return super.importFile(file,redirectAttributes,data);
	}

	@Override
	@RequiresPermissions("teach:tpTeachPatent:view")
	@RequestMapping(value = "export", method=RequestMethod.POST)
	public String exportFile(TpTeachMaterial t, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		return super.exportFile(t,request,response,redirectAttributes);
	}
	
}